using AutoMapper;
using Core.SimpleTemp.Application;
using Core.SimpleTemp.Application.common;
using Core.SimpleTemp.Common.Authorization;
using Core.SimpleTemp.Common.PagingQuery;
using Core.SimpleTemp.Entitys;
using Core.SimpleTemp.Mvc.Api.Internal;
using Core.SimpleTemp.Repositories.Internal;
using Core.Toolkit.Authorization;
using Core.Toolkit.Core;
using Core.Toolkit.Core.Api;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Core.SimpleTemp.Mvc.Api.sys
{
    /// <summary>
    /// FL_System
    ///</summary>
    [ApiExplorerSettings(GroupName = "Sys")]//swagger分类标签
    [Route("api/[controller]")]//路由说明
    [EnableCors("any")]//跨域规则
    [ApiController]//APi标识Controller
    public class FL_SystemController : CoreApiController
    {
        private readonly CoreDBContext _coreDBContext;
        private readonly FL_SystemService _service;
       
        /// <summary>
        /// FL_System
        ///</summary>
        public FL_SystemController(FL_SystemService service, CoreDBContext coreDBContext)
        {
            _service = service;
            _coreDBContext = coreDBContext;
        }

        #region 基础增删改查
        /// <summary>
        /// 查询
        ///</summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>

        [HttpPost("GetList")]
        [PermissionFilter(nameof(FL_SystemController) + "_" + nameof(FL_SystemController.GetList), AuthorizationConst.LIST)]
        public async Task<IActionResult>
            GetList(PagingModel<FL_SystemDto>
                pagingQueryModel)
        {
            ////工厂
          //  pagingQueryModel.Model.CreateFactory = UserIdentity.Factory;

            IPageModel<FL_SystemDto>
                result = await _service.GetList(pagingQueryModel);

            result.PageData.ForEach(dto =>
            {
                var str = "";
                dto.FL_SystemDept.ToList().ForEach(a =>
                {
                    str += _coreDBContext.SysDepartment.Where(x => x.Id == a.DeptId).FirstOrDefault()?.Name + ",";
                });
                if (str.Length > 0)
                    str = str.Substring(0, str.Length - 1);
                dto.Mark03 = str;

            });
            return this.JsonSuccess(result);
        }

        /// <summary>
        /// 添加/修改
        ///</summary>
        /// <param name="dto"></param>
        /// <returns></returns>

        [HttpPost("Save")]
        [PermissionFilter(nameof(FL_SystemController) + "_" + nameof(FL_SystemController.SaveAsync), AuthorizationConst.SAVE)]
        public async Task<IActionResult>
            SaveAsync(FL_SystemDto dto)
        {
            //添加
            if (Equals(dto.Id, Guid.Empty))
            {
                dto.FL_SystemDept.ToList().ForEach(a =>
                {
                    a.SystemId = dto.Id;
                    a.Id = Guid.Empty;
                });
                ////工厂
                dto.CreateFactory = UserIdentity.Factory;
                dto.CreateTime = System.DateTime.Now;
                await _service.InsertAsync(dto);
                return this.JsonSuccess(string.Empty);
            }
            else
            {
                ////工厂
                dto.CreateFactory = UserIdentity.Factory;
                dto.MS_RevisionTime = System.DateTime.Now;
                await _service.UpdateAsync(dto,false, new List<string> { "FL_SystemDept" });
                var oldEntity = await _coreDBContext.FL_SystemDept.Where(x => x.FL_SystemId == dto.Id).ToListAsync();
                oldEntity.ForEach(e => _coreDBContext.FL_SystemDept.Remove(e));
              
                if (dto.FL_SystemDept.Count > 1)
                {
                   var newEntity = Mapper.Map<List<FL_SystemDept>>(dto.FL_SystemDept.Where(x => x.Id == Guid.Empty));
                    newEntity.ForEach(e =>
                    {
                        e.FL_SystemId = dto.Id; e.DeptId = dto.FL_SystemDept.LastOrDefault().DeptId;
                        e.SystemId = dto.Id;
                    });
                    await _coreDBContext.AddRangeAsync(newEntity);
                }
                else if(dto.FL_SystemDept.Count ==1)
                {
                    var newEntity = Mapper.Map<List<FL_SystemDept>>(dto.FL_SystemDept);
                    newEntity.ForEach(e =>
                    {
                        e.FL_SystemId = dto.Id; e.DeptId = dto.FL_SystemDept.LastOrDefault().DeptId;
                        e.SystemId = dto.Id;
                    });
                    await _coreDBContext.AddRangeAsync(newEntity);
                }
             
                await _coreDBContext.SaveChangesAsync();
                return this.JsonSuccess(string.Empty);
            }
        }

        /// <summary>
        /// DeleteMuti
        ///</summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("DeleteMuti")]
        [PermissionFilter(nameof(FL_SystemController) + "_" + nameof(FL_SystemController.DeleteMutiAsync), AuthorizationConst.DELETE)]
        public async Task<IActionResult>
            DeleteMutiAsync([FromBody]Guid[] ids)
        {

            List<Guid> newList = new List<Guid>();
            for (int i = 0; i < ids.Count(); i++)
            {
                if (_coreDBContext.FL_System.Where(x => x.Id == ids[i]).Where(b => b.IsDeleted == false).ToList().Count > 0)
                {
                    newList.Add(ids[i]);
                }
            }
            await _service.DeleteBatchAsync(newList.ToArray());

            return this.JsonSuccess();

        }


        /// <summary>
        /// 根据ID获取信息
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>

        [HttpGet("Get")]
        public async Task<IActionResult> Get(Guid id)
        {
            var model = await _service.GetAsync(id);
            if (model == null) return this.JsonFaild("未找到对应数据:" + id);
            var DepName = "";
            if (model.FL_SystemDept.Count>0)
            {
                if (_coreDBContext.SysDepartment.Where(x => x.Id == model.FL_SystemDept.FirstOrDefault().DeptId).ToList().Count > 0)
                {
                    DepName = _coreDBContext.SysDepartment.Where(x => x.Id == model.FL_SystemDept.FirstOrDefault().DeptId).FirstOrDefault().Name;
                }
            }
            var FileLeveName = "";
            if(model.FL_SystemFileLevel !=null)
            {
                FileLeveName = model.FL_SystemFileLevel.FileLeve;
            }
            var retObj = new
            {
                model.Id,
                model.MS_InstitutionName,//
                model.MS_FileNo,
                FileLeveName,
                fileLeve = model.FileLeve,
                model.MS_ImplementationDate,
                model.MS_ReviewCycle,
                model.MS_ReviewDate,
                model.MS_RevisionTime,
                model.MS_Mark,
                model.Attachment,
                model.AttachmentName,
                model.FL_SystemDept,
                Mark04 = DepName,

            };
            model.FL_SystemDept = retObj.FL_SystemDept;
            return this.JsonSuccess(retObj);
        }


        /// <summary>
        /// 导出
        ///</summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>

        [HttpPost("Export")]
        [PermissionFilter(nameof(FL_SystemController) + "_" + nameof(FL_SystemController.Export), AuthorizationConst.EXPORT)]
        public async Task<IActionResult>
            Export(PagingModel<FL_SystemDto>
                pagingQueryModel)
        {
            var fileName = await _service.Export(pagingQueryModel);
            if (string.IsNullOrWhiteSpace(fileName))
                return this.JsonFaild(NULL_DATA_FOR_EXCEL_EXPORT);
            return this.JsonSuccess(fileName);
        }


        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="data"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("Import")]
        //[PermissionFilter(nameof(FX_EquipmentFacilitiesController) + "_" + "导入")]
        public async Task<IActionResult> ImportAsync([FromForm]String data, [FromForm]List<IFormFile> file)
        {
            var retMeg = await _service.ImportAsync(file[0], data);
            if (!retMeg.Any())
            {
                return this.JsonSuccess();
            }
            else
            {
                return this.JsonFaild(retMeg[0].ToString());
            }
        }
      

        #endregion


    }
}
